#
# tools.py
#
#
# dtd2rep: A simple XML DTD to repository generator. 
#
# Copyright (C) 2004, 2005 Raphael Marvie 
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
# http://www.fsf.org/licensing/licenses/gpl.html
#
# Author contact: raphael.marvie@lifl.fr
#

'''
A simple XML DTD to repository generator. The repository is intended
to ease the browsing and building of XML files offering python objects
for navigation.
'''

import time

import picorine

from dtd2rep_templates import tmpl


__version__ = '0.3.0'
__date__    = 'Wed Apr 27 17:30:24 CEST 2005'
__author__  = 'Raphael Marvie <raphael.marvie@lifl.fr>'


class Dtd2Rep:
    '''Generates a set of classes for representing an XML document as
    a tree of python objects. This generation is based upon the DTD
    definition.
    '''
    
    def __init__ (self, dtd, out):
        '''constructor
        '''
        self.dtd = dtd
        self.out = out

    def _header (self):
        '''
        internal method for file header generation
        '''
        self.out.write (tmpl.header_str %
                        (self.out.name, __version__, time.ctime ()))
        
    def _footer (self):
        '''
        internal method for file footer generation
        '''
        self.out.write (tmpl.footer_str)

    def generate (self):
        '''Entry point for generation
        '''
        self._header ()
        for e in self.dtd.elems.values ():
            name = e.get_name ()
            print 'Generating class for element', name
            self.out.write (tmpl.class_str % (name,))
            for a in e.get_attr_list ():
                self.out.write (tmpl.attr_str % (a,))
            model = e.get_content_model () [1]
            for c in model:
                if c [1] == '*' or c [1] == '+':
                    src = tmpl.elem_multiple_str
                else:
                    src = tmpl.elem_simple_str
                self.out.write (src % (c [0],))
            for c in model:
                if c [1] == '*' or c [1] == '+':
                    src = tmpl.elem_multiple_method_tmpl
                else:
                    src = tmpl.elem_simple_method_tmpl
                self.out.write (src % {'name': c[0]})
        self._footer ()
                
